var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../bd.js')
var router = express.Router()
const md5 = require('md5-nodejs');


// 用户登录
router.post("/login", urlencodedParser, async(req, res) => {
    const { loginName, loginKey } = req.body
    const sql = "select id from user where loginName=? and loginKey=?"
    const r = await db.doSQL(sql, [loginName, loginKey])
    if (r[0]) { //有id
        const token = await getTokenById(r[0].id)
        if (token) {
            res.send(db.handleResults({ token: token }))
        } else {
            // throw error
        }
    } else { //没找到id
        res.send(db.handleNoResults())
    }
})

// // 返回用户角色信息
router.get('/info', async function(req, res) {
    const { token } = req.query;
    const sql = 'select u.id, name, roles, avatar from tokens as t,user as u where t.uid=u.id and t.token=?'
    const r = await db.doSQL(sql, [token])
    console.log(r);
    if (r[0]) {
        res.send(db.handleResults(r[0]))
    } else {
        res.send(db.handleNoResults())
    }
})

// // 退出登录  
router.post("/logout", urlencodedParser, async(req, res) => {
    let { token } = req.body
    let sql = `delete from tokens where token=?`
    console.log(token)
    let r = await db.doSQL(sql, [token])
    if (r.affectedRows == 0) {
        res.send(db.error())
    } else {
        res.send(db.handleResults({}))
    }
})

//  获取tonken  
async function getTokenById(uid) {
    const sql = "select * from tokens where uid =?"
        // const sql = `select * from tokens where uid = '${uid}'`
    const r = await db.doSQL(sql, [uid])
    let token
    if (r.length == 0) { // 没 token
        let newToken = md5('hyx' + uid + Date.now())
        const sql = "insert into tokens (token, uid) values (?,?)"
        const r = await db.doSQL(sql, [newToken, uid])
        console.log(r)
        if (r.affectedRows == 0) {
            token = null
        } else {
            token = newToken
        }
    } else { // 有 token
        token = r[0].token
    }
    return token
}

// 默认导出 相当于 export default
module.exports = router;